package com.hicar.util;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


public class GridPaging {
    private int start=0;
    private int page=0;
    private int length=10;
    private int draw;

    public Pageable genPageable(){
        page = start/length;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if(request.getParameter("order[0][column]")!=null){
            String orderName = request.getParameter("columns["+request.getParameter("order[0][column]").toString()+"][data]");
            Sort.Direction direction = (request.getParameter("order[0][dir]")!=null&&request.getParameter("order[0][dir]").equals("asc"))? Sort.Direction.ASC:Sort.Direction.DESC;
            return new PageRequest(page, length, direction, orderName);
        }
        return new PageRequest(page, length);
    }

    public int getStart() {
        return start;
    }

    public void setStart(int start) {
        this.start = start;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public int getDraw() {
        return draw;
    }

    public void setDraw(int draw) {
        this.draw = draw+1;
    }
}
